<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router';
let route = useRoute()
import { ElMessage } from 'element-plus'
import ElementPlus from 'element-plus'
import EditAllocation from './EditAllocation.vue'
import { getallocationadmin, getallAdminlike, getalldistributorlike, getallenduserlike, getallocationdistributor, getallocationenduser } from '../../api/api'
import data from "@/untils/address/states.json"
const isV3 = ref(false)
let total = ref(0)
let pageSize = ref(10)
import { Decrypt } from '../../untils/passjs/security'

let roleId = ref(0)
let page = ref(1)
let type = ref("")
async function getallocationadminfun() {
    let data = await getallocationadmin(1, roleId.value, page.value, pageSize.value)
    if (data.code == 200) {
        total.value = data.total
        tableData.value = data.rows
    }
}
async function getallocationdistributorfun() {
    let data = await getallocationdistributor(1, roleId.value, page.value, pageSize.value)
    if (data.code == 200) {
        total.value = data.total
        tableData.value = data.rows
    }
}
async function getallocationenduserfun() {
    let data = await getallocationenduser(1, roleId.value, page.value, pageSize.value)
    if (data.code == 200) {
        total.value = data.total
        tableData.value = data.rows
    }
}
onMounted(() => {
    roleId.value = +route.query.roleId;
    type.value = route.params.type
    console.log(type.value);
    console.log(roleId.value);

    if (type.value == "admin") {
        getallocationadminfun()
    } else if (type.value == 'distributor') {
        getallocationdistributorfun()
    } else if (type.value == 'enduer') {
        getallocationenduserfun()
    }

})
import dayjs from 'dayjs';
import { en } from 'element-plus/es/locales.mjs'

// 定义的头部输入框的数据
let topdata = ref({
    nickname: "",
    phone: "",

})
// 表格数据
let tableData = ref([])
//     // 获取页面数据
//     async function getschoolbas(){
//       let {data} = await getschoolbasics()
//       if(data.code == 200){
//          tableData.value = data.data
//          topdata.value.time = dayjs(topdata.value.time).format("YYYY-MM-DD")
//       }
//    }


// 渲染状态的显示
let switchFlag = (flag) => {
    return flag == 0 ? true : false;
}

// 点击查询
//    async function addschoolbaslike(){
//       console.log(topdata.value);
//       topdata.value.time = dayjs(topdata.value.time).format("YYYY-MM-DD")
//       let {data} = await getschoolbasicslike(topdata.value)
//       console.log(data);
//       if(data.code == 200){
//          tableData.value = data.data
//       }
//    }
// 点击取消按钮
//    async function cancel(){
//       topdata.value = {
//         username:"",
//       phone:"",
//       accountNonLocked:"",
//       enabled:""
//       }
//       getschoolbas()
//    }
// 点击状态按钮 切换状态
//    let chuanflag = ref(0)

async function switchchange(userId, accountNonLocked) {
    console.log("1", userId, accountNonLocked);

}
async function switchchangeenabled(userId, enabled) {
    console.log("2", userId, enabled);

}
//    // 删除
//    let dianjiid = ref(0)
const dialogVisible = ref(false)
function del(val) {
    //   dianjiid.value = val.id
    // dialogVisible.value = true
}
async function yesdel() {
    // dialogVisible.value = false
    //   let deldata = await delschoolbas(dianjiid.value)
    //   if(deldata.data.code == 200){
    //      if(deldata.data.data.affectedRows > 0){
    //         ElMessage({
    //            message: '删除成功.',
    //            type: 'success',
    //         })
    //   getschoolbas()
    //      }
    //   }
}

// 遮罩层
let dialogFormVisible = ref(false)
// 定义 是添加还是编辑的字符串
let changeType = ref("")
//    // 添加操作
//    function add(){
//        // 点击添加按钮
// dialogFormVisible.value = true
//       // //让changeType 标识 为add
//         changeType.value = 'add'
//         formlist.value = {
//             school:"",
//             username:"",
//             tel:"",
//             person:"",
//             time:"",
//             pwd:"",
//             flag:1
//          }
//    }

//    onMounted(()=>{
//     //   getschoolbas()
//    })
// 点击重置密码
// let passwordVisible = ref(false)

// 添加这两个变量
const currentUser = ref({})
const passwordVisible = ref(false)

// 修改重置密码函数
function openResetPasswordDialog(user) {
    console.log(user, currentUser.value);

    currentUser.value = user
    passwordVisible.value = true
}
// 1. 定义表单数据
const resetForm = ref({
    newpass: ''
})
// 确认重置密码
function reactpass() {
    passwordVisible.value = false
    // 如果验证通过 则进行一下环节
    resetFormRef.value.validate((valid) => {
        if (valid) {
            // 验证通过
            ElMessage.success('密码格式正确')
            console.log(resetForm.value.newpass);
            resetForm.value.newpass = ""
            // 这里可以执行提交操作
        } else {
            // 验证失败
            return false

        }
    })

}
const resetFormRef = ref(null)
const rulesobj = {
    newpass: [
        {
            required: true,
            message: 'Please input a password',
            trigger: 'blur'
        },
        {
            // pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,16}$/,
            pattern: /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z!@#$%^&*]{8,16}$/,
            message: 'Password requires a combination of 8-16 letters, numbers, and special characters',
            trigger: 'blur'
        }
    ]
}



//  传递参数
let formlist = reactive({})
function add() {
    console.log(dialogFormVisible.value);
    //  //点击添加按钮
    dialogFormVisible.value = !dialogFormVisible.value
    console.log("新增操作");
    // changeType.value = 'add'

}

//     // 子传父的事件，关闭遮罩层
function closechange() {
    dialogFormVisible.value = false
    // getschoolbas()
    // getAdmin()
    if (type.value == "admin") {
        getallocationadminfun(page.value)
    } else if (type.value == 'distributor') {
        getallocationdistributorfun(page.value)
    } else if (type.value == 'enduer') {
        getallocationenduserfun(page.value)
    }

}
let isSearching = ref(false)
async function adminlike() {
    console.log("模糊查询操作");
    isSearching.value = true
    console.log(topdata.value);
    let { nickname, phone } = topdata.value
    if (type.value == 'admin') {
        // admin模糊查询
        let res = await getallAdminlike(nickname, phone, page.value, pageSize.value)
        console.log(res);
        if (res.code == 200) {
            tableData.value = res.rows
            if (res.rows.length == 0) {
                return;
            }
            total.value = res.total
        }
    } else if (type.value == 'distributor') {
        // 分销商模糊查询
        let res = await getalldistributorlike(nickname, phone, page.value, pageSize.value)
        console.log(res);
        if (res.code == 200) {
            tableData.value = res.rows
            if (res.rows.length == 0) {
                return;
            }
            total.value = res.total
        }
    } else if (type.value == 'enduser') {
        // 终端用户模糊查询
        let res = await getallenduserlike(nickname, phone, page.value, pageSize.value)
        console.log(res);
        if (res.code == 200) {
            tableData.value = res.rows
            if (res.rows.length == 0) {
                return;
            }
            total.value = res.total
        }
    }
}
function cancel() {
    console.log("重置操作");
    isSearching.value = false
    topdata.value = {
        nickname: "",
        phone: "",
    }
    if (type.value == "admin") {
        getallocationadminfun(page.value)
    } else if (type.value == 'distributor') {
        getallocationdistributorfun(page.value)
    } else if (type.value == 'enduer') {
        getallocationenduserfun(page.value)
    }
}
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    page.value = e

    if (isSearching.value) {
        await adminlike()
    } else {
        if (type.value == "admin") {
            getallocationadminfun(e)
        } else if (type.value == 'distributor') {
            getallocationdistributorfun(e)
        } else if (type.value == 'enduer') {
            getallocationenduserfun(e)
        }
    }



}
async function outauth(row) {
    console.log(row.userId);
    console.log(roleId.value);
    let val = {
        roleId: roleId.value,
        userIds: [row.userId],
        optType: 7
    }
    console.log("val", val);
    let res = await submitauthorize(val)
    console.log(res);
    if (res.code == 200) {
        ElMessage.success(res.msg)
    }


}
</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>Assigning Users</span>
            </div>
            <div class="cont">
                <div class="one">
                    <!-- 输入用户昵称 -->
                    <div class="select">
                        <el-input v-model="topdata.nickname" class="inp" style="width: 200px"
                            placeholder="Enter user nickname">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <!-- 输入联系方式 -->
                    <div class="select">
                        <el-input v-model="topdata.phone" class="inp" style="width: 260px"
                            placeholder="Enter contact phone/email">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <el-button type="primary" @click="adminlike">query</el-button>
                    <el-button type="primary" @click="cancel">reset</el-button>
                </div>
                <div class="exp">
                    <div class="export-excel">
                        <el-button style="width: 100px" type="primary" @click="add()">
                            <el-icon>
                                <FolderAdd />
                            </el-icon>add
                        </el-button>
                    </div>
                </div>
                <div class="tab">
                    <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true">
                        <el-table-column width="55">
                            <!-- :empty-text="!permissionquery ? '暂无权限查看' : 'NotData'" -->
                            <!-- <template #default="scope" @click="check">

                     </template> -->
                        </el-table-column>
                        <el-table-column property="username" label="name" />
                        <el-table-column property="nickname" label="nickname" />
                        <el-table-column property="phone" label="cell-phone number" />
                        <el-table-column property="email" label="email" />
                        <el-table-column property="gender" label="gender">
                            <template #default="scope">
                                <span>{{ scope.row.gender == 1 ? 'male' : 'female' }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column property="accountNonLocked" label="Lock status">
                            <template #default="scope">
                                <!-- <el-switch :modelValue="switchFlag(scope.row.accountNonLocked)" active-text="enable"
                                    inline-prompt inactive-text="disable"
                                    @click="switchchange(scope.row.userId, scope.row.accountNonLocked)"
                                    class="el-switch">
                                </el-switch> -->
                                <span>{{ switchFlag(scope.row.accountNonLocked) ? 'open' : 'close' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="enabled" label="Startup status">
                            <template #default="scope">
                                <!-- <el-switch :modelValue="switchFlag(scope.row.enabled)" active-text="enable"
                                    inline-prompt inactive-text="disable"
                                    @click="switchchangeenabled(scope.row.userId, scope.row.enabled)" class="el-switch">
                                </el-switch> -->
                                <span>{{ switchFlag(scope.row.enabled) ? 'open' : 'close' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="name" label="operate" width="300">
                            <template #default="scope">
                                <span class="more-button" @click="outauth(scope.row)" style="cursor: pointer;">
                                    revoke
                                </span>
                                <!-- <el-button type="primary" plain @click="edit(scope.$index, scope.row)">修改</el-button> -->
                                <!-- <el-button type="danger" plain @click=del(scope.row)>删除</el-button> -->
                                <!-- 添加“更多”按钮及下拉菜单 -->

                            </template>

                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                        <el-pagination background layout="prev, pager, next" :page-count="total / pageSize"
                            style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
                    </div>
                    <el-dialog v-model="dialogVisible" title="delete" width="500">
                        <span>Are you sure you want to delete it</span>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible = false">cancel</el-button>
                                <el-button type="primary" @click="yesdel()">
                                    sure
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </div>
                <EditAllocation :dialogFormVisible="dialogFormVisible" :changeType="changeType"
                    v-model:formlist="formlist" @close="closechange" :type="type" :roleId="roleId"></EditAllocation>
                <!-- :formlist="formlist" :changeType="changeType" -->
            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
            .one {
                margin: 10px;
                display: flex;
                padding: 10px;

                div {
                    margin-right: 20px;
                }
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }
            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    /* 如果使用 scoped，需要添加 ::v-deep */
    ::v-deep .custom-modal {
        background-color: rgba(0, 0, 0, 0.5);
        /* 设置弹窗背景颜色为半透明 */
    }

    /* 或者更精确的定位 */
    ::v-deep .custom-modal .el-overlay {
        background-color: rgba(0, 0, 0, 0.8);
    }
}
</style>